<script>
import {
	initDeviceInfo
} from '@/library/device.js';
import {
	watch, inject, provide, ref,
	onMounted, onUnmounted, onBeforeMount,
	onBeforeUpdate, onBeforeUnmount, onActivated,
	onDeactivated, onErrorCaptured,
	onRenderTracked, onRenderTriggered,
	defineComponent
} from 'vue';
import { myRequest } from '@/library/request.js';
import { HTTP, API } from '@/library/config.js';
import {
	getUploadCredentials, getViewCredentials,
	getManageCredentials, getFullCredentials
} from '@/library/cos.js';
/**
 * 	在app运行中如果一些必要资源获取失败，则需要重新启动app
 *	1.如果没有运行到onShow,获取资源失败则直接重新启动app
 *	2.如果运行到onShow,则重新获取资源3次，都失败的话模态框提醒用户重新启动app
 *	3.如果运行到onShow,获取资源成功则继续运行
 */
let requestCount = 0;
let isShowModal = false;

// 验证本地token是否有效
const validateLocalToken = () => {
	const tokenInfo = uni.getStorageSync('token');
	const userInfo = uni.getStorageSync('userInfo');
	console.log('tokenInfo', tokenInfo);
	console.log('userInfo', userInfo);
	if (tokenInfo && tokenInfo.token && tokenInfo.expire_time) {
		// 检查token是否在有效期内
		const currentTime = Date.now();
		const expiresTime = tokenInfo.expire_time * 1000; // 转换为毫秒
		console.log('token过期时间:', new Date(expiresTime).toLocaleString());
		console.log('当前时间:', new Date(currentTime).toLocaleString());

		if (currentTime < expiresTime) {
			return true; // token有效
		}
		// 清除过期的token
		uni.removeStorageSync('token');
		uni.removeStorageSync('userInfo');
		return false; // token无效
	} else {
		console.log('本地无token，执行登录');
		return false; // 无token
	}
};

// 执行微信登录流程
const performWechatLogin = () => {
	return new Promise((resolve) => {
		uni.login({
			success(res) {
				console.log('微信登录成功，code:', res.code);
				if (res.code) {
					myRequest({
						url: API.wechatLogin,
						method: 'POST',
						data: { code: res.code },
					}).then(res => {
						console.log('服务器登录响应:', res);
						if (res.success === true) {
							uni.setStorageSync('token', {
								token: res.data.token,
								expire_time: res.data.expire_time,
							});
							uni.setStorageSync('userInfo', res.data.user);
							resolve({ success: true, data: res.data, message: res.message, code: res.code });
						} else {
							resolve({ success: false, data: {}, message: res.message, code: res.code });
						}
					});
				} else {
					resolve({ success: false, data: {}, message: '微信登录失败，未获取到code' });
				}
			},
			fail(err) {
				resolve({ success: false, data: {}, message: '微信登录失败，未获取到code', code: 999 });
			}
		});
	});
};
/**
 * 分别检测四种凭证是否存在，并且持续时间是否大于1800秒，否则重新获取
 */
const initCosCredentials = () => {
	const uploadCredentials = uni.getStorageSync('uploadCredentials');
	const viewCredentials = uni.getStorageSync('viewCredentials');
	const manageCredentials = uni.getStorageSync('manageCredentials');
	const fullCredentials = uni.getStorageSync('fullCredentials');
	if (!(uploadCredentials
		&& uploadCredentials.ExpiredTime
		&& uploadCredentials.ExpiredTime * 1000 > new Date().getTime())) {
		console.log('uploadCredentials过期，重新获取');
		getUploadCredentials();
	}
	if (!(viewCredentials
		&& viewCredentials.ExpiredTime
		&& viewCredentials.ExpiredTime * 1000 > new Date().getTime())) {
		console.log('viewCredentials过期，重新获取');
		getViewCredentials();
	}
	if (!(manageCredentials
		&& manageCredentials.ExpiredTime
		&& manageCredentials.ExpiredTime * 1000 > new Date().getTime())) {
		console.log('manageCredentials过期，重新获取');
		getManageCredentials();
	}
	if (!(fullCredentials
		&& fullCredentials.ExpiredTime
		&& fullCredentials.ExpiredTime * 1000 > new Date().getTime())) {
		console.log('fullCredentials过期，重新获取');
		getFullCredentials();
	}
};

export default defineComponent({
	name: 'App',
	onLaunch: async function () {
		console.log('========== App Launch ==========');
		const startTime = Date.now();
		// 验证本地token
		const isTokenValid = validateLocalToken();

		// 如果token无效，执行登录流程
		if (!isTokenValid) {
			const res = await performWechatLogin();
			if (!res.success) {
				uni.showToast({
					title: res.message,
					icon: 'none'
				});
				return;
			}
		}

		const endTime = Date.now();
		console.log('启动耗时:', endTime - startTime, 'ms');
		console.log('========== App Launch End ==========');
	},
	onShow: function () {
		console.log('========== App Show ==========');


		// 初始化设备信息
		initDeviceInfo();
		// 获取上传凭证
		initCosCredentials();
	},
	onHide: function () {
		console.log('========== App Hide ==========');
	}
})
</script>

<style>
/*每个页面公共css */
</style>
